<template>
	<view class="order-container">
		<nav-bar title="确认订单" />
		<view class="product-section">
			<view class="product-item" v-for="(item, index) in orderItems" :key="index">
				<image class="product-image" :src="item.image" mode="aspectFill"></image>
				<view class="product-info">
					<view class="product-title">{{ item.title }}</view>
					<view class="product-price">
						<text class="price">¥{{ item.price }}</text>
						<text class="quantity">x{{ item.quantity }}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="price-section">
			<view class="price-item">
				<text>商品金额</text>
				<text class="amount">¥{{ totalProductPrice }}</text>
			</view>
			<view class="price-item">
				<text>运费</text>
				<text class="amount">¥{{ shippingFee }}</text>
			</view>
		</view>
		<view class="address-section">
			<view class="section-title">收件地址</view>
			<view class="address-content" @tap="toggleAddressList">
				<text class="placeholder" v-if="!selectedAddress">请点击选择收件地址</text>
				<view class="address-info" v-else>
					<view class="address-text">{{ selectedAddress.fullAddress }}</view>
					<text class="iconfont icon-right"></text>
				</view>
			</view>
		</view>
		<view class="mask" v-if="showAddressList" @tap="toggleAddressList"></view>
		<view class="address-popup" :class="{ show: showAddressList }">
			<view class="popup-header">
				<text class="title">选择地址</text>
				<view class="header-right">
					<text class="manage" @tap="goToAddressManage">地址管理</text>
					<text class="close" @tap="toggleAddressList">✕</text>
				</view>
			</view>
			<view class="address-list">
				<view class="address-item" v-for="address in sortedAddressList" :key="address.id"
					:class="{ active: selectedAddress === address }" @tap="selectAddress(address)">
					<view class="address-info">
						<view class="left-info">
							<text class="name">{{ address.recipientName }}</text>
							<text class="phone">{{ address.recipientPhone }}</text>
						</view>
						<view class="right-info">
							<text v-if="address.tag" class="tag">{{ address.tag }}</text>
							<text v-if="address.isDefault === 1" class="default-tag">默认</text>
						</view>
					</view>
					<text class="address">{{ address.fullAddress }}</text>
					<text class="select-icon" v-if="selectedAddress === address">✓</text>
				</view>
				<view class="empty-address" v-if="addressList.length === 0">
					<text class="empty-icon-text">📍</text>
					<text class="empty-text">暂无收货地址</text>
					<button class="add-address-btn" @tap="goToAddressManage">添加收货地址</button>
				</view>
			</view>
		</view>
		<view class="house-number-section">
			<view class="section-title">门牌号</view>
			<input class="house-number-input" type="text" v-model="houseNumber" placeholder="请输入详细地址，如3号楼5单元203" />
		</view>
		<view class="receiver-section">
			<view class="section-title">收件人</view>
			<input class="receiver-input" type="text" v-model="receiverName" placeholder="请输入收件人姓名" />
		</view>
		<view class="phone-section">
			<view class="section-title">联系电话</view>
			<input class="phone-input" type="number" v-model="phoneNumber" placeholder="请输入联系电话" />
		</view>
		<view class="remark-section">
			<view class="section-title">备注</view>
			<textarea class="remark-input" type="number" v-model="remark" placeholder="请输入备注" />
		</view>
		<view class="bottom-bar">
			<view class="total-section">
				<text>合计：</text>
				<text class="total-price">¥{{ totalPrice }}</text>
			</view>
			<button class="submit-btn" @tap="submitOrder">提交订单</button>
		</view>
	</view>
</template>

<script>
	import NavBar from '@/components/nav-bar/nav-bar.vue'
	export default {
		components: {
			NavBar
		},
		data() {
			return {
				remark: '',
				orderId: null,
				selectedAddress: '',
				houseNumber: '',
				receiverName: '',
				phoneNumber: '',
				orderItems: [], // 订单商品列表
				shippingFee: '0.00', // 运费
				isSubmitting: false, // 添加提交状态标志
				showAddressList: false,
				addressList: []
			}
		},
		computed: {
			totalProductPrice() {
				return this.orderItems.reduce((sum, item) => {
					return sum + (parseFloat(item.price) * item.quantity)
				}, 0).toFixed(2)
			},
			totalPrice() {
				return (parseFloat(this.totalProductPrice) + parseFloat(this.shippingFee)).toFixed(2)
			},
			sortedAddressList() {
				return [...this.addressList].sort((a, b) => {
					// Sort by isDefault (1 first, then 0)
					return (b.isDefault || 0) - (a.isDefault || 0)
				})
			}
		},
		onLoad(options) {
			// 解析传递过来的订单商品数据
			if (options.orderItems) {
				try {
					this.orderItems = JSON.parse(decodeURIComponent(options.orderItems))
				} catch (error) {
					uni.showToast({
						title: '订单数据错误',
						icon: 'none'
					})
				}
			}
			// 加载地址列表
			this.loadAddressList()
		},
		onShow() {
			this.loadAddressList()
		},
		methods: {
			loadAddressList() {
				const userInfoStr = uni.getStorageSync('userInfo')
				let userInfo = null

				if (userInfoStr) {
					try {
						// 如果是字符串，尝试解析
						if (typeof userInfoStr === 'string') {
							const parsed = JSON.parse(userInfoStr)
							// 检查是否是登录响应格式
							if (parsed.code === 200 && parsed.data) {
								userInfo = parsed.data
							} else {
								userInfo = parsed
							}
						} else {
							// 如果不是字符串，直接使用
							userInfo = userInfoStr
						}
					} catch (e) {
						console.error('解析用户信息失败', e)
						// 解析失败时，尝试直接使用
						userInfo = userInfoStr
					}
				}
				const memberId = userInfo.memberId

				uni.request({
					url: `${uni.$config.baseUrl}/address/address/listAll`,
					method: 'GET',
					data: {
						id: memberId
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data && res.data.code === 200) {
							this.addressList = res.data.rows || []

							// 检查是否有地址
							if (this.addressList.length === 0) {
								// 没有地址，提示用户添加
								uni.showModal({
									title: '提示',
									content: '您还没有收货地址，是否现在添加？',
									confirmText: '去添加',
									success: (res) => {
										if (res.confirm) {
											// 用户点击确定，跳转到地址管理页面
											uni.navigateTo({
												url: '/pages/address/address'
											})
										}
									}
								})
								return
							}

							// 自动选择默认地址
							if (this.addressList.length > 0) {
								// 查找默认地址
								const defaultAddress = this.addressList.find(addr => addr.isDefault === 1)
								// 如果有默认地址则选择默认地址，否则选择第一个地址
								this.selectedAddress = defaultAddress || this.addressList[0]

								// 自动填充收件人信息
								if (this.selectedAddress) {
									this.receiverName = this.selectedAddress.recipientName
									this.phoneNumber = this.selectedAddress.recipientPhone
									this.houseNumber = this.selectedAddress.detailAddress || ''
								}
							}
						} else {
							uni.showToast({
								title: res.data.msg || '获取地址列表失败',
								icon: 'none'
							})
						}
					},
					fail: (err) => {
						console.error('获取地址列表失败:', err)
						uni.showToast({
							title: '网络请求失败',
							icon: 'none'
						})
					}
				})
			},
			// 切换地址列表显示状态
			toggleAddressList() {
				this.showAddressList = !this.showAddressList
			},
			// 选择地址
			selectAddress(address) {
				this.selectedAddress = address
				this.receiverName = address.recipientName
				this.phoneNumber = address.recipientPhone
				this.houseNumber = address.detailAddress || ''
				this.showAddressList = false
			},
			// 跳转到地址管理页面
			goToAddressManage() {
				uni.navigateTo({
					url: '/pages/address/address'
				})
			},
			async submitOrder() {
				// 防止重复提交
				if (this.isSubmitting) {
					uni.showToast({
						title: '请勿重复提交',
						icon: 'none'
					})
					return
				}
				// 检查地址列表是否为空
				if (this.addressList.length === 0) {
					uni.showModal({
						title: '提示',
						content: '您还没有收货地址，请先添加收货地址',
						confirmText: '去添加',
						success: (res) => {
							if (res.confirm) {
								uni.navigateTo({
									url: '/pages/address/address'
								})
							}
						}
					})
					return
				}
				if (!this.selectedAddress) {
					uni.showToast({
						title: '请选择收件地址',
						icon: 'none'
					})
					return
				}
				if (!this.houseNumber) {
					uni.showToast({
						title: '请输入门牌号',
						icon: 'none'
					})
					return
				}
				if (!this.receiverName) {
					uni.showToast({
						title: '请输入收件人姓名',
						icon: 'none'
					})
					return
				}
				if (!this.phoneNumber) {
					uni.showToast({
						title: '请输入联系电话',
						icon: 'none'
					})
					return
				}
				// 设置提交状态为true
				this.isSubmitting = true
				// 构造订单数据
				const orderData = {
					techId: uni.getStorageSync('userInfo').techId,
					techName: '',
					receiverName: this.receiverName,
					receiverPhone: this.phoneNumber,
					receiverAddress: this.selectedAddress.fullAddress,
					houseNumber: this.houseNumber,
					totalAmount: parseFloat(this.totalPrice),
					shippingFee: parseFloat(this.shippingFee),
					orderStatus: 0, // 待付款
					payStatus: 0, // 未支付
					shippingStatus: 0, // 未发货
					remark: this.remark,
				}
				uni.showLoading({
					title: '提交中...'
				})
				try {
					// 1. 创建订单
					const orderRes = await uni.request({
						url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder`,
						method: 'POST',
						data: orderData
					})
					if (orderRes.statusCode !== 200 || orderRes.data.code !== 200) {
						throw new Error(orderRes.data.msg || '创建订单失败')
					}
					// 直接获取返回的数据
					const orderId = orderRes.data.data.id
					this.orderId = orderId
					// 生成订单编号 (使用时间戳)
					const orderNo = orderRes.data.data.orderNo
					// 2. 创建订单项
					let orderDesc = null
					let payAmount = 0
					const orderItemPromises = this.orderItems.map(item => {
						const orderItemData = {
							orderId: orderId,
							orderNo: orderNo,
							productId: parseInt(item.id),
							productTitle: item.title,
							productImage: item.image,
							specification: item.specifications || '',
							specificationName: item.specificationName || '',
							price: parseFloat(item.price),
							quantity: parseInt(item.quantity),
							totalAmount: parseFloat((item.quantity * parseFloat(item.price)).toFixed(2)),
							unit: item.unit || '个'
						}
						if (orderDesc) orderDesc += `,${item.title}`
						else orderDesc = item.title
						payAmount += orderItemData.totalAmount
						return uni.request({
							url: `${uni.$config.baseUrl}/supplieItem/supplieItem`,
							method: 'POST',
							data: orderItemData
						})
					})
					const itemResults = await Promise.all(orderItemPromises)
					// 检查所有订单项是否都创建成功
					const hasError = itemResults.some(res => res.statusCode !== 200 || res.data.code !== 200)
					if (hasError) throw new Error('部分订单项创建失败')
					// 3. 调用微信支付接口
					const payRes = await uni.request({
						url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/createWxPayOrder/${orderId}`,
						method: 'POST'
					})
					if (payRes.data.code === 200) {
						if (1 === 1) {
							const paymentData = {
								payAmount: payAmount,
								orderType: 3,
								orderDesc: orderDesc,
								callbackUrl: '/pages/technician/mysupplieOrder?a=1',
								paymentParams: {
									orderId: this.orderId,
									timeStamp: payRes.data.data.timeStamp,
									nonceStr: payRes.data.data.nonceStr,
									package: `prepay_id=${payRes.data.data.prepay_id}`,
									paySign: payRes.data.data.paySign,
								},
							}
							uni.setStorageSync("paymentData", paymentData)
							uni.redirectTo({
								url: '/pages/pay-public/pay-public?login=false',
							})
							return
						}
						const payData = payRes.data.data
						// #ifdef H5
						const isWechatBrowser = /MicroMessenger/i.test(navigator.userAgent)
						if (isWechatBrowser) {
							// 微信公众号H5环境
							if (typeof WeixinJSBridge === 'undefined') {
								// 如果WeixinJSBridge对象不存在，则通过事件监听创建
								document.addEventListener('WeixinJSBridgeReady', () => {
									this.callWechatH5Pay(payData, orderId)
								}, false)
							} else {
								// 如果WeixinJSBridge对象已经存在，直接调用
								this.callWechatH5Pay(payData, orderId)
							}
						} else {
							// 非微信浏览器
							uni.showModal({
								title: '提示',
								content: '请在微信浏览器中打开进行支付',
								showCancel: false,
								success: () => {
									this.isSubmitting = false
								}
							})
						}
						// #endif
						// #ifdef MP-WEIXIN
						// 小程序环境支付
						uni.requestPayment({
							provider: 'wxpay',
							timeStamp: payData.timeStamp,
							nonceStr: payData.nonceStr,
							package: payData.package,
							signType: 'RSA',
							paySign: payData.paySign,
							success: (res) => {
								// 更新订单支付状态为已支付
								this.updateOrderPaymentStatus(orderId, 1)
								uni.showToast({
									title: '支付成功',
									icon: 'success',
									duration: 2000,
									success: () => {
										setTimeout(() => {
											uni.navigateTo({
												url: '/pages/my-orders/my-orders'
											})
										}, 2000)
									}
								})
							},
							fail: (err) => {
								uni.showToast({
									title: err.errMsg === 'requestPayment:fail cancel' ? '支付取消' :
										'支付失败',
									icon: 'none'
								})
								this.isSubmitting = false
							},
							complete: () => {
								this.isSubmitting = false
							}
						})
						// #endif
					} else {
						throw new Error(payRes.data.msg || '支付创建失败')
					}
				} catch (error) {
					uni.hideLoading()
					uni.showToast({
						title: error.message || '提交订单失败',
						icon: 'none'
					})
					this.isSubmitting = false
				}
			},
			// 微信H5支付方法
			callWechatH5Pay(payData, orderId) {
				WeixinJSBridge.invoke(
					'getBrandWCPayRequest', {
						"appId": payData.appId,
						"timeStamp": payData.timeStamp,
						"nonceStr": payData.nonceStr,
						"package": payData.package,
						"signType": "RSA",
						"paySign": payData.paySign
					},
					(res) => {
						if (res.err_msg === "get_brand_wcpay_request:ok") {
							// 支付成功
							uni.showToast({
								title: '支付成功',
								icon: 'success',
								duration: 2000,
								success: () => {
									this.updateOrderPaymentStatus(this.orderId, 1)
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/technician/mysupplieOrder'
										})
									}, 2000)
								}
							})
						} else if (res.err_msg === "get_brand_wcpay_request:cancel") {
							// 用户取消支付
							uni.showToast({
								title: '支付已取消',
								icon: 'none'
							})
							this.isSubmitting = false
						} else {
							// 支付失败
							uni.showToast({
								title: '支付失败',
								icon: 'none'
							})
							console.error('微信支付失败:', res.err_msg)
							this.isSubmitting = false
						}
					}
				)
			},
			// 更新订单支付状态
			updateOrderPaymentStatus(orderId, paymentStatus) {
				if (!orderId) {
					return
				}
				uni.request({
					url: `${uni.$config.baseUrl}/supplieOrder/supplieOrder/updatePaymentStatus`,
					method: 'POST',
					data: {
						orderId: orderId,
						paymentStatus: paymentStatus
					},
					success: (res) => {
						if (res.statusCode === 200 && res.data.code === 200) {
							// 在订单支付成功的情况下，清空本地购物车缓存
							if (paymentStatus === 1) {
								try {
									// H5 环境
									if (typeof localStorage !== 'undefined') {
										localStorage.removeItem('supplieCart')
									}
									// 小程序及其他环境
									if (typeof uni !== 'undefined' && uni.removeStorageSync) {
										uni.removeStorageSync('supplieCart')
									}
								} catch (e) {
									console.error('清空购物车缓存失败:', e)
								}
							}
						} else {
							console.error('订单支付状态更新失败:', res.data.message || '未知错误')
						}
					},
					fail: (err) => {
						console.error('更新订单支付状态请求失败:', err)
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.order-container {
		min-height: 100vh;
		background: #F5F5F5;
		padding-bottom: 140rpx;
		padding: 20rpx;
	}

	.address-section,
	.house-number-section,
	.receiver-section,
	.phone-section,
	.product-section,
	.price-section,
	.remark-section {
		background: #FFFFFF;
		margin-bottom: 30rpx;
		padding: 40rpx;
		border-radius: 20rpx;
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.05);
	}

	.section-title {
		font-size: 36rpx;
		color: #333333;
		font-weight: 600;
		margin-bottom: 30rpx;
	}

	.address-content {
		.placeholder {
			color: #999999;
			font-size: 36rpx;
		}

		.address-info {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.address-text {
				flex: 1;
				font-size: 36rpx;
				color: #333333;
				line-height: 1.6;
			}

			.iconfont {
				color: #2B87FF;
				font-size: 40rpx;
			}
		}
	}

	.house-number-input,
	.receiver-input,
	.phone-input {
		width: 100%;
		height: 100rpx;
		font-size: 36rpx;
		color: #333333;
		padding: 0 30rpx;
		background: #F8F8F8;
		border-radius: 16rpx;
	}

	.product-section {
		.product-item {
			display: flex;
			align-items: center;
			padding: 30rpx 0;
			border-bottom: 2rpx solid #F5F5F5;

			&:last-child {
				border-bottom: none;
				padding-bottom: 0;
			}

			&:first-child {
				padding-top: 0;
			}

			.product-image {
				width: 180rpx;
				height: 180rpx;
				border-radius: 16rpx;
				margin-right: 30rpx;
				box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
				object-fit: contain;
				background-color: #f8f8f8;
			}

			.product-info {
				flex: 1;

				.product-title {
					font-size: 36rpx;
					color: #333333;
					margin-bottom: 20rpx;
					line-height: 1.4;
					font-weight: 500;
				}

				.product-price {
					display: flex;
					justify-content: space-between;
					align-items: center;

					.price {
						font-size: 40rpx;
						color: #FF0000;
						font-weight: bold;
					}

					.quantity {
						font-size: 36rpx;
						color: #666666;
						margin-right: 10rpx;
					}
				}
			}
		}
	}

	.price-section {
		.price-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-bottom: 30rpx;
			font-size: 36rpx;
			color: #333333;

			&:last-child {
				margin-bottom: 0;
			}

			.amount {
				color: #FF0000;
				font-weight: 500;
			}
		}
	}

	.bottom-bar {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		height: 7%;
		background: #FFFFFF;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 40rpx;
		box-shadow: 0 -6rpx 20rpx rgba(0, 0, 0, 0.08);

		.total-section {
			font-size: 36rpx;
			color: #333333;

			.total-price {
				font-size: 46rpx;
				color: #FF0000;
				font-weight: bold;
			}
		}

		.submit-btn {
			width: 280rpx;
			height: 90rpx;
			line-height: 90rpx;
			background: #2B87FF;
			color: #FFFFFF;
			font-size: 38rpx;
			border-radius: 45rpx;
			text-align: center;
			margin: 0;
			padding: 0;
			box-shadow: 0 8rpx 16rpx rgba(43, 135, 255, 0.25);
			transition: transform 0.3s ease;
			font-weight: 500;

			&:active {
				transform: scale(0.96);
				background: #1A76EE;
			}

			&::after {
				border: none;
			}
		}
	}

	.address-popup {
		position: fixed;
		left: 0;
		right: 0;
		bottom: 0;
		background: #FFFFFF;
		border-radius: 30rpx 30rpx 0 0;
		transform: translateY(100%);
		transition: transform 0.3s ease;
		z-index: 1001;
		box-shadow: 0 -15rpx 40rpx rgba(0, 0, 0, 0.15);

		&.show {
			transform: translateY(0);
		}

		.popup-header {
			display: flex;
			align-items: center;
			justify-content: space-between;
			padding: 40rpx;
			border-bottom: 2rpx solid #EEEEEE;

			.title {
				font-size: 40rpx;
				color: #333;
				font-weight: 600;
			}

			.header-right {
				display: flex;
				align-items: center;

				.manage {
					font-size: 36rpx;
					color: #2B87FF;
					margin-right: 36rpx;
				}

				.close {
					font-size: 48rpx;
					color: #999;
					padding: 10rpx;
				}
			}
		}

		.address-list {
			padding: 20rpx 0;
			max-height: 60vh;
			overflow-y: auto;

			.address-item {
				position: relative;
				padding: 40rpx 40rpx;
				border-bottom: 2rpx solid #EEEEEE;
				transition: all 0.3s ease;

				&:last-child {
					border-bottom: none;
				}

				.address-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 20rpx;

					.left-info {
						display: flex;
						align-items: center;

						.name {
							font-size: 36rpx;
							color: #333;
							margin-right: 24rpx;
							font-weight: 500;
						}

						.phone {
							font-size: 34rpx;
							color: #666;
						}
					}

					.right-info {
						display: flex;
						align-items: center;
						gap: 16rpx;

						.tag {
							font-size: 28rpx;
							color: #2B87FF;
							background: rgba(43, 135, 255, 0.1);
							padding: 8rpx 20rpx;
							border-radius: 8rpx;
						}

						.default-tag {
							font-size: 28rpx;
							color: #FF6B35;
							background: rgba(255, 107, 53, 0.1);
							padding: 8rpx 20rpx;
							border-radius: 8rpx;
						}
					}
				}

				.address {
					font-size: 34rpx;
					color: #666;
					line-height: 1.6;
				}

				.select-icon {
					position: absolute;
					right: 40rpx;
					top: 50%;
					transform: translateY(-50%);
					font-size: 48rpx;
					color: #2B87FF;
				}

				&.active {
					background: #F0F8FF;

					.name {
						color: #2B87FF;
					}
				}

				&:active {
					transform: scale(0.98);
					opacity: 0.9;
				}
			}

			.empty-address {
				display: flex;
				flex-direction: column;
				align-items: center;
				justify-content: center;
				padding: 80rpx 0;

				.empty-icon-text {
					font-size: 100rpx;
					color: #999;
					margin-bottom: 40rpx;
				}

				.empty-text {
					font-size: 36rpx;
					color: #999;
					margin-bottom: 40rpx;
				}

				.add-address-btn {
					width: 400rpx;
					height: 90rpx;
					line-height: 90rpx;
					background: #2B87FF;
					color: #FFFFFF;
					font-size: 36rpx;
					border-radius: 45rpx;
					text-align: center;
					margin: 0;
					padding: 0;
					box-shadow: 0 8rpx 16rpx rgba(43, 135, 255, 0.25);

					&::after {
						border: none;
					}

					&:active {
						transform: scale(0.96);
						background: #1A76EE;
					}
				}
			}
		}
	}

	.mask {
		position: fixed;
		left: 0;
		right: 0;
		top: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		z-index: 1000;
	}
</style>